package ar.edu.unq.leezsi.utils;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public class CookieUtils {

	public static final String REQUEST_PARAM_COOKIE = "Rqtck";
	private final List<Cookie> cookies;

	private final HttpServletRequest request;

	public CookieUtils(HttpServletRequest request) {
		this.cookies = new ArrayList<Cookie>();
		Cookie[] tmpCookies = request.getCookies();
		if (tmpCookies != null) {
			for (Cookie cookie : tmpCookies) {
				this.cookies.add(cookie);
			}
		}
		this.request = request;
	}

	public Cookie at(String name) {

		for (Cookie cookie : this.cookies) {
			if (cookie.getName().equals(name)) {
				return cookie;
			}
		}
		return null;
	}

	public boolean contains(String name) {
		for (Cookie cookie : this.cookies) {
			if (cookie.getName().equals(name)) {
				return true;
			}
		}
		return false;
	}

	public Cookie getFromCookieOrRequest(String name) {
		if (this.contains(name)) {
			return this.at(name);
		}
		Object val = this.request.getAttribute(name);
		if (val != null) {
			Cookie cookie = new Cookie(name, (String) val);
			cookie.setComment(REQUEST_PARAM_COOKIE);
			return cookie;
		}
		return null;
	}

}
